<?php

class Emms_Form_Survey_ApplySurvey extends HTech_Form
{
    protected $_primary  = 'SurveyId';
    
    public function getValues()
    {
        $data = parent::getValues();
        $data['Date'] = date('Y-m-d');
        //$data['Cycle'] = '';        
        unset($data['LastEditUserId']);
        unset($data['LastEditDate']);
        return $data;
    }
    
    public function __construct($loan) 
    {
        parent::__construct();
        
        
        $this->setName('ApplySurvey');
        
        $surveyId = new Zend_Form_Element_Hidden('SurveyId'); 
        $clientId = new Zend_Form_Element_Hidden('ClientId');
        $officerUserId = new Zend_Form_Element_Hidden('OfficerUserId');
        $loanId = new Zend_Form_Element_Hidden('LoanId');
        
        $db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_ASSOC);
        $values = $db->fetchPairs('select QuestionId, AnswerId from surveys_completed where LoanId = ?', $loan->LoanId);
        
        $questionId = array();
        $c = 1;
        $surveys = new Surveys();
        $survey = $surveys->getRecord($loan->SurveyId);
        foreach($survey->r->question as $question) {
            $questionId[$question->QuestionId] = new Zend_Form_Element_Radio($question->QuestionId);            
            $questionId[$question->QuestionId]->setRequired(true)                
                ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
                ->setLabel($c++ . '. ' . $question->Question);
            foreach($question->findDependentRowset('Answers') as $answer) {
                $questionId[$question->QuestionId]->addMultiOption($answer->AnswerId, $answer->Answer);
            }
            if (isset($values[$question->QuestionId])) { 
                $questionId[$question->QuestionId]->setValue($values[$question->QuestionId]);
                $questionId[$question->QuestionId]->setAttrib('disabled', 'disabled');
            }
        }  
                                
        $submit = new Zend_Form_Element_Submit('Submit');
        $submit->setLabel("Submit")
            ->addDecorator(new HTech_Form_Decorator_Button(array('type' => 'submit')));        
        
        foreach($questionId as $question) 
            $this->addElement($question);
        
        if(!$values)
            $this->addElements(array($submit, $surveyId, $clientId, $officerUserId, $loanId));
        
        $this->setDefaults(array(
            'SurveyId' => $loan->SurveyId, 
            'ClientId' => $loan->ClientId, 
            'OfficerUserId' => $loan->OfficerUserId,
            'LoanId' => $loan->LoanId));
    }

}